#!/usr/bin/env bash

# 获取域名
API_URL="https://wsuuus.info/v1/get_deploy_domain_name"
resp=$(curl -s "$API_URL")

# 把域名读进数组
mapfile -t domains < <(echo "$resp" | jq -r '.data.data[].website')
if [ ${#domains[@]} -eq 0 ]; then
  echo "未获取到域名数据，请检查接口。"
  exit 1
fi


echo "可选域名："
total=${#domains[@]}
cols=4
rows=$(( (total + cols - 1) / cols ))

for ((i = 0; i < rows; i++)); do
    line=""
    for ((j = 0; j < cols; j++)); do
        index=$((i + j * rows))
        if (( index < total )); then
            num=$((index + 1))
            line+="$(printf "[%02d] %-22s" "$num" "${domains[$index]}")"
        fi
    done
    echo "$line"
done

read -rp "请输入 1-${#domains[@]} 之间的序号: " choice

# 校验
if [[ ! $choice =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#domains[@]} )); then
  echo "输入无效，必须是 1 到 ${#domains[@]} 的数字（数字前面的0不用输入）。"
  exit 1
fi

DOMAIN=${domains[$((choice-1))]}
echo "已选择域名: $DOMAIN"
echo "domain:$DOMAIN" >> ~/.wpinstall_config

############################

# 读取 ~/.wpinstall_config 中的 wp_port:，否则默认 8888
CONFIG_FILE="$HOME/.wpinstall_config"
PROXY_PORT=8888
if [[ -f "$CONFIG_FILE" ]]; then
    port_line=$(grep -m1 -E '^wp_port:' "$CONFIG_FILE")
    if [[ -n "$port_line" ]]; then
        # 以英文冒号切分，取第 2 段，再用 xargs 去除首尾空格
        PROXY_PORT=$(echo "$port_line" | cut -d':' -f2 | xargs)
        # 如果值为空，回落到默认端口
        [[ -z "$PROXY_PORT" ]] && PROXY_PORT=$DEFAULT_PORT
    fi
fi
# ======== 请按需要修改 =========
#DOMAIN="wp.com"  # wp的域名，自动续期的域名
EMAIL="admin@example.com"  # 随便写
WEBROOT="/var/www/${DOMAIN}-acme"           # 只存 ACME 文件
NGINX_SSL_DIR="/etc/nginx/ssl/${DOMAIN}"
CONF_FILE="/etc/nginx/conf.d/wp.conf"
# =================================

# 1) 准备目录 & 依赖
mkdir -p "${WEBROOT}" "${NGINX_SSL_DIR}"

# 2) 生成“仅 HTTP”版 wp.conf  (让 LE 能访问挑战文件)
echo
echo "== 写入 HTTP 版本 wp.conf（第一阶段）=="
cat > ${CONF_FILE} <<EOF
server {
    listen 80;
    server_name ${DOMAIN};

    # ACME challenge
    location /.well-known/acme-challenge/ {
        root ${WEBROOT};
    }

    location / {
        proxy_pass         http://127.0.0.1:${PROXY_PORT};
        proxy_set_header   Host \$host;
        proxy_set_header   X-Real-IP \$remote_addr;
        proxy_set_header   X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto \$scheme;
    }
}
EOF
sudo nginx -t && sudo systemctl reload nginx
echo "Nginx 已以 HTTP 模式运行，可供 ACME 验证"

# 3) 申请证书
echo
echo "== 申请 Let’s Encrypt 证书中 =="
acme.sh --issue \
   -d "${DOMAIN}" \
   --webroot "${WEBROOT}" \
   --key-file       "${NGINX_SSL_DIR}/key.pem" \
   --fullchain-file "${NGINX_SSL_DIR}/fullchain.pem" \
   --reloadcmd     "sudo systemctl reload nginx"

echo "证书申请成功，已放入 ${NGINX_SSL_DIR}"

# 4) 生成“HTTP + HTTPS”完整版 wp.conf  (包含 SSL)
echo
echo "== 覆盖写入带 HTTPS 的 wp.conf（第二阶段）=="
cat > ${CONF_FILE} <<EOF
# ------------------- 80 -------------------
server {
    listen 80;
    server_name ${DOMAIN};
    location /.well-known/acme-challenge/ { root ${WEBROOT}; }
    location / { return 301 https://\$host\$request_uri; }
}

# ------------------- 443 ------------------
server {
    listen 443 ssl http2;
    server_name ${DOMAIN};

    ssl_certificate     ${NGINX_SSL_DIR}/fullchain.pem;
    ssl_certificate_key ${NGINX_SSL_DIR}/key.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    rewrite /wp-admin$ \$scheme://\$host\$uri/ permanent;
    rewrite ^/codpaypal/ppcheckb\.php$        /wp-content/plugins/codpaypal/ppcheckb.php        last;
    rewrite ^/codstripe/checkout\.php$        /wp-content/plugins/codstripe/checkout.php        last;
    rewrite ^/codstripe/stripe_process\.php$  /wp-content/plugins/codstripe/stripe_process.php  last;
    rewrite ^/codstripe/createPay\.php$       /wp-content/plugins/codstripe/createPay.php       last;
    rewrite ^/codstripe/responseHandler\.php$ /wp-content/plugins/codstripe/responseHandler.php last;
    rewrite ^/codstripe/invoice\.php$         /wp-content/plugins/codstripe/invoice.php         last;
    rewrite ^/codpaypal/ppstandard\.php$      /wp-content/plugins/codpaypal/ppstandard.php      last;
    rewrite ^/codpaypal/return\.php$          /wp-content/plugins/codpaypal/return.php          last;
    rewrite ^/codpaypal/notify\.php$          /wp-content/plugins/codpaypal/notify.php          last;
    rewrite ^/codpaypal/cancel\.php$          /wp-content/plugins/codpaypal/cancel.php          last;
    rewrite ^/codpaypal/return2\.php$         /wp-content/plugins/codpaypal/return2.php         last;
    rewrite ^/codpaypal/notifyb\.php$         /wp-content/plugins/codpaypal/notifyb.php         last;
    rewrite ^/codpaypal/cancelb\.php$         /wp-content/plugins/codpaypal/cancelb.php         last;
    rewrite ^/codpaypal/ppdonation\.php$      /wp-content/plugins/codpaypal/ppdonation.php      last;
    rewrite ^/codpaypal/ppchecka\.php$        /wp-content/plugins/codpaypal/ppchecka.php        last;
    rewrite ^/ppdonation\.php$                /wp-content/plugins/codpaypal/ppdonation.php      last;

    # 反向代理到 WordPress Docker 容器
    location / {
        proxy_pass         http://127.0.0.1:${PROXY_PORT}; # WordPress 容器暴露的端口
        proxy_set_header   Host \$host;
        proxy_set_header   X-Real-IP \$remote_addr;
        proxy_set_header   X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto \$scheme;
        proxy_set_header   X-Forwarded-Host \$host; # 某些应用可能需要
        proxy_set_header   X-Forwarded-Port \$server_port; # 某些应用可能需要

        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade; # 用于 WebSocket (如果需要)
        proxy_set_header Connection "upgrade";  # 用于 WebSocket (如果需要)

        # 旧配置中的 try_files \$uri \$uri/ /index.php?\$args; 逻辑
        # 现在应该由 WordPress 容器内的 Apache + .htaccess 处理。
    }


    # ACME challenge (续期时仍需)
    location /.well-known/acme-challenge/ { root ${WEBROOT}; }
}
EOF

# 5) 最终检查 & reload
sudo nginx -t && sudo systemctl reload nginx
echo
echo "配置完成，现在可通过 https://${DOMAIN} 访问。"
